const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");

const app = express();
const upload = multer({ dest: "uploads/" });

app.post("/upload", upload.single("file"), (req, res) => {
  const { chunkIndex, totalChunks, fileName } = req.body;
  const targetPath = path.join(__dirname, "uploads", fileName);

  // Move the chunk to the target file path
  fs.rename(req.file.path, targetPath + ".part" + chunkIndex, (err) => {
    if (err) return res.status(500).send("Error saving chunk");

    // Check if all chunks are uploaded
    if (parseInt(chunkIndex) + 1 === parseInt(totalChunks)) {
      // Merge chunks
      mergeChunks(targetPath, totalChunks, fileName);
    }

    res.status(200).send("Chunk uploaded successfully");
  });
});

function mergeChunks(targetPath, totalChunks, fileName) {
  const writeStream = fs.createWriteStream(targetPath);

  for (let i = 0; i < totalChunks; i++) {
    const chunkPath = targetPath + ".part" + i;
    const chunkStream = fs.createReadStream(chunkPath);
    chunkStream.pipe(writeStream, { end: false });

    chunkStream.on("end", () => {
      fs.unlinkSync(chunkPath); // 删除已合并的分片
    });
  }

  writeStream.on("finish", () => {
    console.log(`${fileName} uploaded successfully!`);
  });
}

app.listen(3000, () => {
  console.log("Server is running on http://localhost:3000");
});
